package com.xiaoyu.lanling.feature.login.activity

import android.os.Bundle
import com.xiaoyu.base.data.UserData
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.app.AppHelper
import com.xiaoyu.lanling.event.login.*
import com.xiaoyu.lanling.feature.login.fragment.LoginCellphoneFragment
import com.xiaoyu.lanling.feature.login.fragment.LoginCodeFragment
import com.xiaoyu.lanling.view.FragmentAdapter
import com.xiaoyu.lanling.view.OnShowFragment
import kotlinx.android.synthetic.main.activity_login_cellphone.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class LoginCellphoneActivity : AppCompatToolbarActivity() {

    private val fragmentList: MutableList<OnShowFragment> = mutableListOf()

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_login_cellphone)

        initViewPager()
        initEvent()
    }

    override fun onResumeSafelyAfterAppFinishInit(isFirstTimeResume: Boolean) {
        super.onResumeSafelyAfterAppFinishInit(isFirstTimeResume)

        // Avoid IM and etc. has been login after register not complete, then return to LoginActivity
        if (UserData.getInstance().hasLogin()) {
            AppHelper.afterLogout()
        }
    }

    private fun initViewPager() {
        val titles: MutableList<CharSequence> = mutableListOf()
        titles.add("cellphone")
        titles.add("code")
        fragmentList.add(LoginCellphoneFragment.newInstance())
        fragmentList.add(LoginCodeFragment.newInstance())
        val fragmentAdapter = FragmentAdapter(supportFragmentManager, fragmentList, titles)
        view_pager.offscreenPageLimit = fragmentList.size
        view_pager.adapter = fragmentAdapter
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: LoginCellphoneClickNextEvent) {
                if (fragmentList[view_pager.currentItem] is LoginCellphoneFragment) {
                    view_pager.currentItem = view_pager.currentItem + 1
                }
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: LoginCodeClickBackEvent) {
                if (fragmentList[view_pager.currentItem] is LoginCodeFragment) {
                    view_pager.currentItem = view_pager.currentItem - 1
                }
            }
        })
    }
}